/**
 * WMS拣货系统配置文件
 * 参考KWKC项目格式，集中管理所有明道云工作表的字段ID
 */

// 环境读取工具（支持多别名、带回退）
const readEnv = (ids = [], fallback = '') => {
  try {
    let cfg = null;
    if (typeof window !== 'undefined') {
      const candidates = [window, window.parent, window.top].filter(Boolean)
      for (const w of candidates) {
        // 兼容多种注入位置：mdye.env.config（已发布）、mdye.env（开发调试）、window.env（极个别场景）
        const c1 = w && w.mdye && w.mdye.env && w.mdye.env.config ? w.mdye.env.config : null
        const c2 = !c1 && w && w.mdye && w.mdye.env ? w.mdye.env : null
        const c3 = !c1 && !c2 && w && w.env ? w.env : null
        const c = c1 || c2 || c3
        if (c) { cfg = c; break }
      }
    }
    if (!cfg) return fallback;
    const idList = Array.isArray(ids) ? ids : [ids];
    for (const key of idList) {
      if (!key) continue;
      // 支持点语法、下划线语法、原样
      if (cfg[key] != null && cfg[key] !== '') return cfg[key];
      const underscoreKey = String(key).replaceAll('.', '_');
      if (cfg[underscoreKey] != null && cfg[underscoreKey] !== '') return cfg[underscoreKey];
    }
    return fallback;
  } catch (_) {
    return fallback;
  }
};

// 延迟求值工具：通过 getter 在“使用时”读取 mdye.env.config
const lazyGetter = (ids, fallback = '') => ({
  get value() {
    return readEnv(ids, fallback);
  }
});

// 工作表ID配置（来自 mdye.env.config，可回退到默认值）
export const WORKSHEET_IDS = {
  // 拣货单管理表（变量id：JHworksheetId）
  get PICKING_ORDERS() { return readEnv('JHworksheetId', ''); },
  // 拣货详情表（变量id：JHXworksheetId）
  get PICKING_DETAILS() { return readEnv('JHXworksheetId', ''); },
  // 库位库存关联表（变量id：KWKCworksheetId）
  get LOCATION_STOCK() { return readEnv('KWKCworksheetId', ''); },
  // 容器管理表（变量id：QrworksheetId）
  get CONTAINER_MANAGEMENT() { return readEnv('QrworksheetId', ''); }
};

// 视图ID配置
export const VIEW_IDS = {
  // 拣货单默认视图（变量id：JHview）
  get PICKING_ORDERS_DEFAULT() { return readEnv('JHview', ''); },
  // 库位库存默认视图（允许外部配置，可留空）
  get LOCATION_STOCK_DEFAULT() { return readEnv('LOCATION_STOCK_DEFAULT', ''); }
};

// API配置（变量id：apiAddress、apiUser、AppKey、Sign、SecretKey 及 webhookURL 系列）
export const API_CONFIG = {
  get baseURL() { return readEnv(['apiAddress', 'API_BASE_URL'], 'https://www.dachen.vip/api/v2/open/worksheet'); },
  get userInfoURL() { return readEnv(['apiUser', 'API_USER_URL'], 'https://www.dachen.vip/api/v2/open/user'); },
  // 去拣货（绑定拣货人员）
  get webhookURL() { return readEnv(['webhookURL'], ''); },
  // 提交拣货：兼容你当前变量ID completeWebhook
  get submitWebhookURL() { return readEnv(['submitWebhookURL', 'completeWebhook'], ''); },
  // 绑定容器：兼容你当前变量ID rqWebhook（已取消“拣货完成”功能）
  get completeWebhookURL() { return readEnv(['completeWebhookURL', 'rqWebhook'], ''); },
  get appKey() { return readEnv('AppKey', ''); },
  get sign() { return readEnv('Sign', ''); },
  get secretKey() { return readEnv('SecretKey', ''); }
};

// 调试快照：返回关键配置（敏感值打码）
export const getConfigSnapshot = () => {
  const mask = v => (typeof v === 'string' && v.length > 8) ? `${v.slice(0,4)}***${v.slice(-4)}` : (v ?? '')
  try {
    const cfg = (typeof window !== 'undefined' && ((window.mdye && window.mdye.env && window.mdye.env.config) || (window.parent && window.parent.mdye && window.parent.mdye.env && window.parent.mdye.env.config) || (window.top && window.top.mdye && window.top.mdye.env && window.top.mdye.env.config))) || {}
    return {
      keys: Object.keys(cfg || {}),
      values: {
        apiAddress: API_CONFIG.baseURL,
        apiUser: API_CONFIG.userInfoURL,
        AppKey: mask(API_CONFIG.appKey),
        Sign: mask(API_CONFIG.sign),
        SecretKey: mask(API_CONFIG.secretKey),
        JHworksheetId: mask(WORKSHEET_IDS.PICKING_ORDERS),
        JHview: mask(VIEW_IDS.PICKING_ORDERS_DEFAULT)
      }
    }
  } catch (e) {
    return { keys: [], values: {} }
  }
}

// 供应商相关字段
export const SUPPLIER_FIELDS = {
  // 供应商名称（支持参数覆盖：SUPPLIER_FIELDS_NAME / SUPPLIER_FIELDS.NAME / SUPPLIER_NAME）
  get NAME() { return readEnv(['SUPPLIER_FIELDS_NAME', 'SUPPLIER_FIELDS.NAME', 'SUPPLIER_NAME'], ''); }
};

// 商品信息字段
export const PRODUCT_FIELDS = {
  get NAME() { return readEnv(['PRODUCT_FIELDS_NAME', 'PRODUCT_FIELDS.NAME', 'PRODUCT_NAME'], ''); },
  get BARCODE() { return readEnv(['PRODUCT_FIELDS_BARCODE', 'PRODUCT_FIELDS.BARCODE', 'PRODUCT_BARCODE'], ''); },
  get BATCH_CODE() { return readEnv(['PRODUCT_FIELDS_BATCH_CODE', 'PRODUCT_FIELDS.BATCH_CODE', 'PRODUCT_BATCH_CODE'], ''); },
  get PRODUCTION_DATE() { return readEnv(['PRODUCT_FIELDS_PRODUCTION_DATE', 'PRODUCT_FIELDS.PRODUCTION_DATE', 'PRODUCT_PRODUCTION_DATE'], ''); }
};

// 订单信息字段
export const ORDER_FIELDS = {
  get SHIPPING_DESTINATION() { return readEnv(['ORDER_FIELDS_SHIPPING_DESTINATION', 'ORDER_FIELDS.SHIPPING_DESTINATION', 'ORDER_SHIPPING_DESTINATION'], ''); },
  get OUTBOUND_PLAN_NUMBER() { return readEnv(['ORDER_FIELDS_OUTBOUND_PLAN_NUMBER', 'ORDER_FIELDS.OUTBOUND_PLAN_NUMBER', 'ORDER_OUTBOUND_PLAN_NUMBER'], ''); },
  get PICKING_TYPE() { return readEnv(['ORDER_FIELDS_PICKING_TYPE', 'ORDER_FIELDS.PICKING_TYPE', 'ORDER_PICKING_TYPE'], ''); },
  get DOCUMENT_TYPE() { return readEnv(['ORDER_FIELDS_DOCUMENT_TYPE', 'ORDER_FIELDS.DOCUMENT_TYPE', 'ORDER_DOCUMENT_TYPE'], ''); }
};

// 拣货数量字段
export const QUANTITY_FIELDS = {
  get REQUIRED() { return readEnv(['QUANTITY_FIELDS_REQUIRED', 'QUANTITY_FIELDS.REQUIRED', 'QUANTITY_REQUIRED'], ''); },
  get PLANNED_OUTBOUND() { return readEnv(['QUANTITY_FIELDS_PLANNED_OUTBOUND', 'QUANTITY_FIELDS.PLANNED_OUTBOUND', 'QUANTITY_PLANNED_OUTBOUND'], ''); },
  get PICKED() { return readEnv(['QUANTITY_FIELDS_PICKED', 'QUANTITY_FIELDS.PICKED', 'QUANTITY_PICKED'], ''); },
  get STATUS() { return readEnv(['QUANTITY_FIELDS_STATUS', 'QUANTITY_FIELDS.STATUS', 'QUANTITY_STATUS'], ''); },
  get CONTAINER_CODE() { return readEnv(['QUANTITY_FIELDS_CONTAINER_CODE', 'QUANTITY_FIELDS.CONTAINER_CODE', 'QUANTITY_CONTAINER_CODE'], ''); }
};

// 库位信息字段
export const LOCATION_FIELDS = {
  get CODE() { return readEnv(['LOCATION_FIELDS_CODE', 'LOCATION_FIELDS.CODE', 'LOCATION_CODE'], ''); },
  get STOCK() { return readEnv(['LOCATION_FIELDS_STOCK', 'LOCATION_FIELDS.STOCK', 'LOCATION_STOCK'], ''); },
  get PICKING_LOCATION_REF() { return readEnv(['LOCATION_FIELDS_PICKING_LOCATION_REF', 'LOCATION_FIELDS.PICKING_LOCATION_REF', 'LOCATION_PICKING_LOCATION_REF'], ''); }
};

// 库位库存表字段
export const LOCATION_STOCK_FIELDS = {
  get LOCATION_CODE() { return readEnv(['LOCATION_STOCK_FIELDS_LOCATION_CODE', 'LOCATION_STOCK_FIELDS.LOCATION_CODE', 'LOCATION_STOCK_LOCATION_CODE'], ''); },
  get PRODUCT_NAME() { return readEnv(['LOCATION_STOCK_FIELDS_PRODUCT_NAME', 'LOCATION_STOCK_FIELDS.PRODUCT_NAME', 'LOCATION_STOCK_PRODUCT_NAME'], ''); },
  get SUPPLIER_NAME() { return readEnv(['LOCATION_STOCK_FIELDS_SUPPLIER_NAME', 'LOCATION_STOCK_FIELDS.SUPPLIER_NAME', 'LOCATION_STOCK_SUPPLIER_NAME'], ''); },
  get PRODUCTION_DATE() { return readEnv(['LOCATION_STOCK_FIELDS_PRODUCTION_DATE', 'LOCATION_STOCK_FIELDS.PRODUCTION_DATE', 'LOCATION_STOCK_PRODUCTION_DATE'], ''); },
  get STOCK_QUANTITY() { return readEnv(['LOCATION_STOCK_FIELDS_STOCK_QUANTITY', 'LOCATION_STOCK_FIELDS.STOCK_QUANTITY', 'LOCATION_STOCK_STOCK_QUANTITY'], ''); },
  get LOCKED_STOCK() { return readEnv(['LOCATION_STOCK_FIELDS_LOCKED_STOCK', 'LOCATION_STOCK_FIELDS.LOCKED_STOCK', 'LOCATION_STOCK_LOCKED_STOCK'], ''); }
};

// 容器管理表字段
export const CONTAINER_FIELDS = {
  get CONTAINER_CODE() { return readEnv(['CONTAINER_FIELDS_CONTAINER_CODE', 'CONTAINER_FIELDS.CONTAINER_CODE', 'CONTAINER_CODE'], ''); },
  get STATUS() { return readEnv(['CONTAINER_FIELDS_STATUS', 'CONTAINER_FIELDS.STATUS', 'CONTAINER_STATUS'], ''); },
  get DELIVERY_STATION() { return readEnv(['CONTAINER_FIELDS_DELIVERY_STATION', 'CONTAINER_FIELDS.DELIVERY_STATION', 'CONTAINER_DELIVERY_STATION'], ''); }
};

// 排除的库位编码
export const EXCLUDED_LOCATIONS = [
  'JH-01-01-01-01',
  'CP-01-01-01-01', 
  'SH-01-01-01-01',
  'CY-01-01-01-01'
];

// 分页配置
export const PAGINATION_CONFIG = {
  DEFAULT_PAGE_SIZE: 50,
  MAX_PAGE_SIZE: 200
};

// 字段映射工具函数 - 支持两种数据格式
export const getFieldValue = (data, fieldId, defaultValue = '') => {
  if (!data || !fieldId) {
    return defaultValue;
  }
  
  // 新格式：数据直接作为对象属性
  if (typeof data === 'object' && !Array.isArray(data)) {
    return data[fieldId] || defaultValue;
  }
  
  // 旧格式：controls数组格式
  if (Array.isArray(data)) {
    const field = data.find(control => control.controlId === fieldId);
    return field ? (field.value || defaultValue) : defaultValue;
  }
  
  return defaultValue;
};

// 根据字段名称获取值（备用方案）- 支持两种数据格式
export const getFieldValueByName = (data, fieldName, defaultValue = '') => {
  if (!data || !fieldName) {
    return defaultValue;
  }
  
  // 新格式：暂不支持按名称查找（因为明道云直接返回字段ID作为key）
  if (typeof data === 'object' && !Array.isArray(data)) {
    // 可能需要遍历寻找，但这里先返回默认值
    return defaultValue;
  }
  
  // 旧格式：controls数组格式
  if (Array.isArray(data)) {
    const field = data.find(control => control.controlName === fieldName);
    return field ? (field.value || defaultValue) : defaultValue;
  }
  
  return defaultValue;
};

// 智能字段值获取（尝试多种方式）
export const getFieldValueSmart = (data, fieldId, fieldNames = [], defaultValue = '') => {
  // 首先尝试通过字段ID获取
  let value = getFieldValue(data, fieldId, null);
  if (value !== null && value !== '') {
    return value;
  }
  
  // 然后尝试通过字段名称获取
  for (const fieldName of fieldNames) {
    value = getFieldValueByName(data, fieldName, null);
    if (value !== null && value !== '') {
      return value;
    }
  }
  
  return defaultValue;
};

// 数据转换函数
export const transformPickingOrderData = (rows) => {
  if (!rows || !Array.isArray(rows)) {
    console.warn('transformPickingOrderData: rows is not an array:', typeof rows, rows);
    return [];
  }
  
  console.log('transformPickingOrderData: 处理', rows.length, '条拣货单记录');
  
  return rows.map((row, index) => {
    // 明道云新格式：数据直接作为对象属性，不再有controls数组
    
    // 获取供应商名称 - 直接使用row作为数据源
    const supplierName = getFieldValueSmart(
      row,
      SUPPLIER_FIELDS.NAME,
      ['供应商名称', '供应商', 'supplier_name', 'supplier'],
      '未知供应商'
    );
    
    // 获取商品名称 - 直接使用row作为数据源
    const productName = getFieldValueSmart(
      row,
      PRODUCT_FIELDS.NAME,
      ['商品名称', '产品名称', 'product_name', 'name'],
      '未知商品'
    );
    
    // 获取发运目的地
    const shippingDestination = getFieldValueSmart(
      row,
      ORDER_FIELDS.SHIPPING_DESTINATION,
      ['发运目的地', '配送站点', 'shipping_destination', 'destination'],
      '未指定'
    );
    
    // 获取出库计划单号（替换批次码）
    const outboundPlanNumber = getFieldValueSmart(
      row,
      ORDER_FIELDS.OUTBOUND_PLAN_NUMBER,
      ['出库计划单号', '计划单号', 'outbound_plan', 'plan_number'],
      'N/A'
    );
    
    // 获取拣货类型
    const pickingType = getFieldValueSmart(
      row,
      ORDER_FIELDS.PICKING_TYPE,
      ['拣货类型', '类型', 'picking_type', 'type'],
      '标准拣货'
    );
    
    // 获取单据类型
    const documentType = getFieldValueSmart(
      row,
      ORDER_FIELDS.DOCUMENT_TYPE,
      ['单据类型', '文档类型', 'document_type', 'doc_type'],
      '标准单据'
    );
    
    // 获取数量信息，优先使用计划出库数字段
    
    // 首先尝试获取计划出库数
    const plannedOutboundQuantity = parseInt(getFieldValueSmart(
      row,
      QUANTITY_FIELDS.PLANNED_OUTBOUND,
      ['计划出库数', '计划出库数量', 'planned_outbound', 'planned_quantity'],
      '0'
    )) || 0;
    
    // 获取应拣货数（用作备用）
    let requiredQuantityFieldNames = ['应拣货数', '需拣货数', 'required_quantity'];
    let pickedQuantityFieldNames = ['已拣货数', '已拣数量', 'picked_quantity'];
    
    // 对残品出库类型添加额外的字段名称搜索
    if (pickingType === '残品出库') {
      requiredQuantityFieldNames = [
        '应拣货数', '需拣货数', 'required_quantity',
        '应出库数', '需出库数', 'outbound_quantity',
        '残品数量', '残品出库数量', 'defective_quantity'
      ];
      pickedQuantityFieldNames = [
        '已拣货数', '已拣数量', 'picked_quantity',
        '已出库数', '已出库数量', 'outbound_picked',
        '已处理数量', 'processed_quantity'
      ];
    }
    
    const requiredQuantityFromField = parseInt(getFieldValueSmart(
      row,
      QUANTITY_FIELDS.REQUIRED,
      requiredQuantityFieldNames,
      '0'
    )) || 0;
    
    // 优先使用计划出库数，如果为0则使用应拣货数
    const requiredQuantity = plannedOutboundQuantity > 0 ? plannedOutboundQuantity : requiredQuantityFromField;
    
    const pickedQuantity = parseInt(getFieldValueSmart(
      row,
      QUANTITY_FIELDS.PICKED,
      pickedQuantityFieldNames,
      '0'
    )) || 0;
    
    // 获取状态
    const rawStatus = getFieldValueSmart(
      row,
      QUANTITY_FIELDS.STATUS,
      ['状态', 'status'],
      ''
    );
    
    // 状态映射和标准化
    let status;
    if (rawStatus) {
      const statusStr = String(rawStatus).toLowerCase();
      if (statusStr.includes('完成') || statusStr.includes('completed') || statusStr === '已完成' || statusStr === '3') {
        status = 'completed';
      } else if (statusStr.includes('待确认') || statusStr.includes('pending_confirm') || statusStr === '待确认' || statusStr === '5') {
        status = 'pending_confirm';
      } else if (statusStr.includes('进行') || statusStr.includes('progress') || statusStr === '拣货中' || statusStr === '2') {
        status = 'in_progress';
      } else if (statusStr.includes('取消') || statusStr.includes('cancelled') || statusStr === '已取消' || statusStr === '4') {
        status = 'cancelled';
      } else {
        status = 'pending';
      }
    } else {
      // 如果没有状态字段，根据数量判断
      status = pickedQuantity >= requiredQuantity ? 'completed' : 'pending';
    }
    
    // 获取商品条码
    const barcode = getFieldValueSmart(
      row,
      PRODUCT_FIELDS.BARCODE,
      ['商品条码', '条码', 'barcode'],
      ''
    );
    
    // 获取生产日期
    const productionDate = getFieldValueSmart(
      row,
      PRODUCT_FIELDS.PRODUCTION_DATE,
      ['生产日期', 'production_date'],
      ''
    );
    
    // 获取库位信息
    const location = getFieldValueSmart(
      row,
      LOCATION_FIELDS.CODE,
      ['库位', '库位编码', 'location', 'location_code'],
      ''
    );
    
    const locationStock = parseInt(getFieldValueSmart(
      row,
      LOCATION_FIELDS.STOCK,
      ['库位存放数量', '库存数量', 'location_stock', 'stock'],
      '0'
    )) || 0;
    
    // 获取容器码
    const containerCode = getFieldValueSmart(
      row,
      QUANTITY_FIELDS.CONTAINER_CODE,
      ['容器码', 'container_code'],
      ''
    );
    
    const result = {
      id: row.rowid || '',
      supplierName: supplierName,
      productName: productName,
      shippingDestination: shippingDestination, // 新增：发运目的地
      outboundPlanNumber: outboundPlanNumber, // 新增：出库计划单号（替换批次码）
      pickingType: pickingType, // 新增：拣货类型
      documentType: documentType, // 新增：单据类型
      requiredQuantity: requiredQuantity,
      plannedOutboundQuantity: plannedOutboundQuantity, // 新增：计划出库数
      pickedQuantity: pickedQuantity,
      status: status,
      barcode: barcode,
      productionDate: productionDate,
      location: location,
      locationStock: locationStock,
      containerCode: containerCode, // 新增：容器码
      remainingQuantity: Math.max(0, (requiredQuantity || 0) - (pickedQuantity || 0)),
      rawData: row
    };
    
    // 仅在需要调试时输出第一条记录
    if (index === 0) {
      console.log('第一条记录转换结果:', {
        id: result.id,
        supplierName: result.supplierName,
        productName: result.productName,
        pickingType: result.pickingType,
        documentType: result.documentType,
        barcode: result.barcode,
        productionDate: result.productionDate,
        plannedOutboundQuantity: plannedOutboundQuantity,
        requiredQuantityFromField: requiredQuantityFromField,
        finalRequiredQuantity: result.requiredQuantity,
        pickedQuantity: result.pickedQuantity,
        remainingQuantity: result.remainingQuantity,
        status: result.status
      });
      console.log('字段ID验证:', {
        '商品名称字段ID': PRODUCT_FIELDS.NAME,
        '计划出库数字段ID': QUANTITY_FIELDS.PLANNED_OUTBOUND,
        '应拣数字段ID': QUANTITY_FIELDS.REQUIRED,
        '已拣数字段ID': QUANTITY_FIELDS.PICKED,
        '商品条码字段ID': PRODUCT_FIELDS.BARCODE,
        '生产日期字段ID': PRODUCT_FIELDS.PRODUCTION_DATE
      });
      
      // 验证配置的字段ID是否正确获取到值
      console.log('=== 字段值验证 ===');
      console.log(`拣货类型: ${pickingType}`);
      console.log(`计划出库数字段(${QUANTITY_FIELDS.PLANNED_OUTBOUND}):`, row[QUANTITY_FIELDS.PLANNED_OUTBOUND]);
      console.log(`应拣货数字段(${QUANTITY_FIELDS.REQUIRED}):`, row[QUANTITY_FIELDS.REQUIRED]);
      console.log(`已拣货数字段(${QUANTITY_FIELDS.PICKED}):`, row[QUANTITY_FIELDS.PICKED]);
      console.log(`商品条码字段(${PRODUCT_FIELDS.BARCODE}):`, row[PRODUCT_FIELDS.BARCODE]);
      console.log(`生产日期字段(${PRODUCT_FIELDS.PRODUCTION_DATE}):`, row[PRODUCT_FIELDS.PRODUCTION_DATE]);
      console.log(`数量选择逻辑: 计划出库数=${plannedOutboundQuantity}, 应拣货数=${requiredQuantityFromField}, 最终使用=${requiredQuantity}`);
      console.log(`剩余数量计算: ${requiredQuantity} - ${pickedQuantity} = ${result.remainingQuantity}`);
      
      // 对残品出库类型进行特殊调试
      if (pickingType === '残品出库') {
        console.log('=== 残品出库特殊调试 ===');
        console.log('使用的应拣货数字段名:', requiredQuantityFieldNames);
        console.log('使用的已拣货数字段名:', pickedQuantityFieldNames);
        console.log('原始数据键值:', Object.keys(row));
      }
      console.log('==================');
    }
    
    return result;
  }).filter(item => item !== null);
};

// 数据类型常量（明道云API规范）
export const DATA_TYPES = {
  TEXT: 2,        // 文本
  NUMBER: 6,      // 数字
  DATE: 15,       // 日期
  DATETIME: 16,   // 日期时间
  ATTACHMENT: 14  // 附件
};

// 过滤条件类型（明道云API规范）
export const FILTER_TYPES = {
  EQUAL: 1,       // 等于
  CONTAINS: 2,    // 包含
  NOT_EQUAL: 3,   // 不等于
  GREATER: 4,     // 大于
  LESS: 5,        // 小于
  IS_EMPTY: 6,    // 为空
  IS_NOT_EMPTY: 7 // 不为空
};

// 配置验证函数
export const validateConfig = () => {
  const errors = [];
  
  // 检查工作表ID
  if (!WORKSHEET_IDS.PICKING_ORDERS) {
    errors.push('缺少拣货单工作表ID');
  }
  
  // 检查供应商字段ID
  if (!SUPPLIER_FIELDS.NAME) {
    errors.push('缺少供应商名称字段ID');
  }
  
  return {
    isValid: errors.length === 0,
    errors
  };
};

// 导出所有配置
export default {
  WORKSHEET_IDS,
  VIEW_IDS,
  API_CONFIG,
  SUPPLIER_FIELDS,
  PRODUCT_FIELDS,
  ORDER_FIELDS,
  QUANTITY_FIELDS,
  LOCATION_FIELDS,
  LOCATION_STOCK_FIELDS,
  CONTAINER_FIELDS,
  PAGINATION_CONFIG,
  getFieldValue,
  getFieldValueByName,
  getFieldValueSmart,
  transformPickingOrderData,
  validateConfig,
  DATA_TYPES,
  FILTER_TYPES
};